import { v4 as uuidv4 } from "uuid"; // 随机生成uuid
import { loginAsync } from "../http/api/login";
// 字符串转为ArrayBuffer
function textToArrayBuffer(s) {
  var i = s.length;
  var n = 0;
  var ba = new Array();
  for (var j = 0; j < i; ) {
    var c = s.codePointAt(j);
    if (c < 128) {
      ba[n++] = c;
      j++;
    } else if (c > 127 && c < 2048) {
      ba[n++] = (c >> 6) | 192;
      ba[n++] = (c & 63) | 128;
      j++;
    } else if (c > 2047 && c < 65536) {
      ba[n++] = (c >> 12) | 224;
      ba[n++] = ((c >> 6) & 63) | 128;
      ba[n++] = (c & 63) | 128;
      j++;
    } else {
      ba[n++] = (c >> 18) | 240;
      ba[n++] = ((c >> 12) & 63) | 128;
      ba[n++] = ((c >> 6) & 63) | 128;
      ba[n++] = (c & 63) | 128;
      j += 2;
    }
  }
  return new Uint8Array(ba).buffer;
}

// byte数组转字符串
function byteToString(arr) {
  if (typeof arr === "string") {
    return arr;
  }
  let str = "";
  let _arr = arr;
  for (var i = 0; i < _arr.length; i++) {
    var one = _arr[i].toString(2),
      v = one.match(/^1+?(?=0)/);
    if (v && one.length == 8) {
      var bytesLength = v[0].length;
      var store = _arr[i].toString(2).slice(7 - bytesLength);
      for (var st = 1; st < bytesLength; st++) {
        store += _arr[st + i].toString(2).slice(2);
      }
      str += String.fromCharCode(parseInt(store, 2));
      i += bytesLength - 1;
    } else {
      str += String.fromCharCode(_arr[i]);
    }
  }
  return str;
}

// 将发送的消息封装成字节流
function messageToByte(body, messageType) {
  let strBuffer = new Uint8Array(textToArrayBuffer(JSON.stringify(body))); // 内容buffer数组
  let arraybuffer = new ArrayBuffer(strBuffer.length + 44);
  let unit8Arr = new Uint8Array(arraybuffer);
  // 魔术值
  unit8Arr[0] = 0;
  unit8Arr[1] = 6;
  unit8Arr[2] = 1;
  unit8Arr[3] = 2;
  // 版本数
  unit8Arr[4] = 1;
  // 序列化方式
  unit8Arr[5] = 1;
  // 消息类型
  unit8Arr[6] = messageType;
  // uuid
  for (let i = 7; i < 39; i++) {
    unit8Arr[i] = body.sequenceId.charAt(i - 7).charCodeAt();
  }
  // 无意义字节
  unit8Arr[39] = 255;
  // 内容长度
  let number2 = strBuffer.length.toString(2).toString();
  let length = number2.length;
  if (length < 32) {
    for (let i = 0; i < 32 - length; i++) {
      number2 = "0" + number2;
    }
  }
  unit8Arr[40] = parseInt(number2.slice(0, 8), 2);
  unit8Arr[41] = parseInt(number2.slice(8, 16), 2);
  unit8Arr[42] = parseInt(number2.slice(16, 24), 2);
  unit8Arr[43] = parseInt(number2.slice(24, 32), 2);
  // 将内容字节插入总的buffer
  for (let i = 0; i < strBuffer.length; i++) {
    unit8Arr[i + 44] = strBuffer[i];
  }
  return arraybuffer;
}
// 生成uuid
function setUuid() {
  let uuid = uuidv4();
  return uuid.split("-").join("");
}

// 心跳机制
var timeInterval = null;
function startHeart(websocket) {
  // 心跳函数需要发送的数据
  let uuid = setUuid(); // 随机生成uuid
  let body = {
    messageType: 14,
    sequenceId: uuid,
  };
  let messageType = 14;
  let messageBuffer = messageToByte(body, messageType); // 封装字节流

  timeInterval = setInterval(() => {
    console.log("心跳函数发送的字节流", messageBuffer);
    console.log("状态", websocket.readyState);
    websocket.send(messageBuffer);
  }, 3000);
}
// 停止心跳函数
function stopHeart() {
  clearInterval(timeInterval);
}

// 登录
async function login(username, password, callback) {
  let params = {
    username: username,
    password: password,
  };
  const data = await loginAsync(params);
  callback("登录成功");
}

// 连接成功后将token发送给服务器
function sendToken(websocket, token, messageType) {
  let uuid = setUuid(); // 随机生成uuid
  let body = {
    messageType: messageType,
    sequenceId: uuid,
    token: token,
  };
  let messageBuffer = messageToByte(body, messageType); // 封装字节流
  websocket.send(messageBuffer); // 发送消息
}


export {
  textToArrayBuffer,
  messageToByte,
  byteToString,
  setUuid,
  startHeart,
  stopHeart,
  login,
  sendToken,
};
